<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" >
      <el-form-item label="调薪调整" prop="salaryAdjust">
        <el-select  style="width: 3.55rem" v-model="queryParams.salaryAdjust" placeholder="请选择" :disabled='isdisabled'>
          <el-option
            v-for="dict in dict.type.salary_adjust_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table @cell-dblclick="handleCellDoubleClick" v-loading="loading" :data="humanSalaryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180px" sortable/>
      <el-table-column label="申请人姓名" align="center" prop="applicantName" width="180px" sortable/>
      <el-table-column label="部门" align="center" prop="departName" width="120px" sortable/>
      <el-table-column label="薪资调整" align="center" prop="salaryAdjust" width="120px" sortable>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.salary_adjust_type" :value="scope.row.salaryAdjust"/>
        </template>
      </el-table-column>
      <el-table-column label="调薪前工资" align="center" prop="beforeSalary" width="180px" sortable/>
      <el-table-column label="调薪后工资" align="center" prop="afterSalary" width="180px" sortable/>
<!--      <el-table-column label="创建时间" align="center" prop="createTime" width="180px" sortable/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.actBusinessStatus.status!=='draft' || scope.row.actBusinessStatus.status==='cancel' || scope.row.actBusinessStatus.status==='back'"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改调薪申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :before-close="cancel">
      <el-tabs  type="border-card" >
        <el-tab-pane label="业务单据" v-loading="loading">
          <el-form ref="form" :model="form" :rules="rules" label-width="150px">
            <el-form-item label="编号" prop="number">
              <el-input  v-model="form.numberNum" disabled  style="width: 3.55rem"/>
            </el-form-item>
            <el-form-item label="调薪人" prop="applicantName" class="textarea">
              <el-input v-model="form.applicantName" readonly :disabled='isdisabled' placeholder="请输入" style="width: 3.55rem" >
                <el-button type="primary" :disabled="isdisabled" slot="append" @click="openUserSelect" v-text="btnText"></el-button>
                <el-button type="success" :disabled="isdisabled" slot="append" @click="clearUserSelect">清空</el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="部门" prop="deptName">
              <el-select v-model="form.deptName"
                         style="width: 3.55rem"
                         :disabled='isdisabled'
                         placeholder="请选择" clearable>
                <el-option
                  v-for="item in deptList"
                  :key="item.deptName"
                  :label="item.deptName"
                  :value="item.deptName"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="薪资调整" prop="salaryAdjust" style="width: 100%">
              <el-select v-model="form.salaryAdjust" style="width: 3.55rem" placeholder="请选择" :disabled='isdisabled' clearable>
                <el-option
                  v-for="item in dict.type.salary_adjust_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <!--              <el-input :disabled='isdisabled' v-model="form.salaryAdjust" placeholder="请输入" />-->
            </el-form-item>
            <el-form-item label="调薪前工资" prop="beforeSalary" style="width: 100%">
              <el-input :disabled='isdisabled' style="width: 3.55rem" v-model="form.beforeSalary"
                        @input="form.beforeSalary=form.beforeSalary.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                        placeholder="请输入">
                <i slot="suffix" style="font-style:normal;">元</i>
              </el-input>
            </el-form-item>
            <el-form-item label="调薪后工资" prop="afterSalary" style="width: 100%">
              <el-input :disabled='isdisabled' style="width: 3.55rem" v-model="form.afterSalary"
                        @input="form.afterSalary=form.afterSalary.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                        placeholder="请输入" >
                <i slot="suffix" style="font-style:normal;">元</i>
              </el-input>
            </el-form-item>
            <el-form-item label="上传附件" prop="attachment">
              <fileUpload v-model="form.attachment" :isDisabled="isdisabled" :limit="5"/>
            </el-form-item>
          </el-form>

        </el-tab-pane>
        <!-- 审批历史 -->
        <el-tab-pane label="审批历史" v-if="processInstanceId">
          <history ref="historyRef" :processInstanceId="processInstanceId" ></history>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 选择人员 -->
    <sys-dept-user ref="userRef" :multiple="false" @confirmUser="clickUser" :propUserList = 'propUserList'/>

  </div>
</template>

<script>
import { listHumanSalary, getHumanSalary, delHumanSalary, addHumanSalary, updateHumanSalary } from "@/api/oa/humanSalary";
import processApi from "@/api/workflow/processInst";
import history from "@/components/Process/History.vue";
import verify from "@/components/Process/Verify.vue";
import {parseTime} from "@/utils/ruoyi";
import {listAll} from "@/api/system/dept";
import SysDeptUser from "@/views/components/user/sys-dept-user.vue";
export default {
  name: "HumanSalary",
  dicts: ['sys_user_sex','act_status','salary_adjust_type'],
  components: {
    SysDeptUser,
    history,
    verify
  },
  data() {
    return {
      btnText:"选择",
      height:`calc(100% - 88px)`,
      projectNameList: [],
      isdisabled:false,
      // 流程实例
      processInstanceId: '',
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      propUserList:[],
      deptList:[],
      // 调薪申请表格数据
      humanSalaryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        submitTimeList: [],
        createBy:'',
        status:'',
        adjustType: undefined,
        sex: undefined,
        entryTime: undefined,
        beforeDept: undefined,
        afterDept: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        adjustType: [
          { required: true, message: "调薪类型不能为空", trigger: "change" }
        ],
        applicantName: [
          { required: true, message: "申请人姓名不能为空", trigger: "blur" }
        ],
        applicantId: [
          { required: true, message: "申请人id不能为空", trigger: "blur" }
        ],
        salaryAdjust: [
          { required: true, message: "薪资调整不能为空", trigger: "blur" }
        ],
        beforeSalary: [
          { required: true, message: "调薪前工资不能为空", trigger: "blur" }
        ],
        afterSalary: [
          { required: true, message: "调薪后工资不能为空", trigger: "blur" }
        ],
      },
      taskVariables: {}, //流程变量
      taskId: undefined, //任务id
      flag: true,
      // 消息提醒
      sendMessage: {},
      processKey: 'oa_human_salary',
    };
  },
  created() {
    const userId = this.$route.params && this.$route.params.userId;
    if (userId){
      this.queryParams.applicantId=userId;
    }
    this.getList();
  },
  mounted() {
    this.$nextTick(() => {
      this.queryParams.projectName=this.projectNameByList;
    },300)
  },
  methods: {
    /** 查询调薪申请列表 */
    getList() {
      this.loading = true;
      // this.queryParams.applicantId=this
      this.queryParams.status="finish";
      listHumanSalary(this.queryParams).then(response => {
        this.humanSalaryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.listAll();
    },
    // 取消按钮
    cancel() {
      this.isdisabled=false
      this.open = false;
      this.reset();
    },
    clearUserSelect(){
      this.form.applicantId="";
      this.form.applicantName="";
    },
    clickUser(userList){
      let arrAssignee= userList.map(item => {
        return item.nickName
      })
      let arrAssigneeId= userList.map(item => {
        return item.userId
      })
      let resultAssignee = arrAssignee.join(",")
      let resultAssigneeId = arrAssigneeId.join(",")
      this.$set(this.form,'applicantName',resultAssignee)
      this.$set(this.form,'applicantId',resultAssigneeId)
      this.$refs.userRef.visible = false
      this.$forceUpdate()
      // this.getUser(resultAssigneeId);
    },
    listAll(){
      listAll().then(res=>{
        console.log(res.data)
        this.deptList=res.data;
      })
    },
    openUserSelect(){
      this.propUserList = [];
      if(this.form.applicantId){
        let userIds = this.form.applicantId.split( ',' )
        if(userIds.length>0){
          this.propUserList = userIds
        }
      }
      this.$refs.userRef.visible = true
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deptId: undefined,
        userId: undefined,
        adjustType: undefined,
        effectDate: undefined,
        applicantName: undefined,
        applicantId: undefined,
        salaryAdjust:undefined,
        createBy: undefined,
        beforeSalary:undefined,
        afterSalary:undefined,
        updateBy: undefined,
        createTime: undefined,
        updateTime: undefined,
      };
      this.processInstanceId = undefined
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      if (selection.length==1){
        if (selection[0].actBusinessStatus.status=='draft'||selection[0].actBusinessStatus.status=='back'||selection[0].actBusinessStatus.status=='cancel'){
        }else {
          this.single=true;
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.flag = true
      this.reset();
      this.open = true;
      this.title = "添加调薪申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.flag = true
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getHumanSalary(id).then(response => {
        this.loading = false;
        this.form = response.data;
        if (response.data.actBusinessStatus.createTime){
          this.form.numberNum=this.processKey + '@' + parseTime(response.data.actBusinessStatus.createTime, '{y}{m}{d}{h}{i}{s}')
        }
        this.$nextTick(() => {
          this.processInstanceId=response.data.actBusinessStatus.processInstanceId
        })
        this.open = true;
        this.title = "修改调薪申请";
        this.sendMessage = {
          title:'调薪申请',
          messageContent:'单据【'+row.id+"】申请"
        }
      });
    },
    handleCellDoubleClick(row, column, event) {
      // 双击事件处理逻辑
      this.handleView(row);
    },
    //查看
    handleView(row){
      this.flag = false
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getHumanSalary(id).then(response => {
        this.loading = false;
        this.form = response.data;
        if (response.data.actBusinessStatus.createTime){
          this.form.numberNum=this.processKey + '@' + parseTime(response.data.actBusinessStatus.createTime, '{y}{m}{d}{h}{i}{s}')
        }
        this.$nextTick(() => {
          this.processInstanceId=response.data.actBusinessStatus.processInstanceId
        })
        this.isdisabled=true
        this.open = true;
        this.title = "查看调薪申请业务";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除调薪申请编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delHumanSalary(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/humanSalary/export', {
        ...this.queryParams
      }, `humanSalary_${new Date().getTime()}.xlsx`)
    },
    //提交流程
    submitFormApply(entity){
      //流程变量
      this.taskVariables = {
        entity: entity,
        maximumValue:this.maximumValue
      }
      const data = {
        processKey: this.processKey, // key
        businessKey: entity.id, // 业务id
        variables: this.taskVariables,
        classFullName: 'com.ruoyi.oa.domain.OaPurchaseParity'
      }
      // 启动流程
      processApi.startProcessApply(data).then(response => {
        this.taskId = response.data.taskId;
        this.$refs.verifyRef.visible = true
        this.$refs.verifyRef.reset()
      })
    },
    //撤回
    cancelProcessApply(row){
      this.$modal.confirm('是否撤销申请').then(() => {
        this.loading = true;
        return processApi.cancelProcessApply(row.actBusinessStatus.processInstanceId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤回成功");
      }).finally(() => {
        this.loading = false;
      });
    },
  }
};
</script>
<style scoped>
.main{
  height: 100%;
}
/* 设置滚动条宽度和高度 */
::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 8px; /* 横向滚动条 */
  height: 8px; /* 纵向滚动条 必写 */
}
/* 设置滚动条样式 */
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #dde;
  border-radius: 3px;
}
#selectForm >>> .el-form-item__label {
  font-size: 12px;
}
::v-deep .bjsm .el-form-item__content{
  width: calc(100% - 130px) !important;
}
</style>
